<template>
  <div class="test-list">
    <el-table
      v-loading="loading"
      :data="list"
    >
      <el-table-column prop="id" label="ID" align="center" />
      <el-table-column label="测试类型" align="center">
        <template v-slot="{ row }">
          {{ row.chapter_id ? '章节小测' : '课程测试' }}
        </template>
      </el-table-column>
      <el-table-column label="所属章节" align="center">
        <template v-slot="{ row }">
          {{ row?.chapter?.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="test_title" label="测试名称" align="center" />
      <el-table-column prop="pass_rate" label="及格线" align="center" />
      <el-table-column prop="created_at" label="创建时间" align="center" width="150px" />
      <el-table-column label="操作" align="center">
        <template v-slot="{ row }">
          <el-button
            type="text"
            :disabled="!row.is_update"
            @click="openEditCourseTestDialog(row.id)"
          >
            编辑
          </el-button>
          <el-button
            :disabled="!row.is_update"
            type="text"
            style="color: #F56C6C;"
            @click="removeCourseTest(row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <CreateTestDialog
      ref="createTestDialogRef"
      v-model="visible"
      @onConfirm="editCourseTest"
    />

  </div>
</template>
<script>
import { getCourseTestList, getCourseTestDetails, editCourseTest, deleteCourseTest } from '@/api/v2/course'
import CreateTestDialog from './CreateTestDialog.vue'
import { value, isArrayEqual } from '@/utils/kris_utils'
import { cloneDeep } from 'lodash-es'
export default {
  name: '',
  components: {
    CreateTestDialog
  },
  props: {
    courseId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      visible: false,
      testDetails: {
        unitTestId: null,
        backup: null,
        data: {}
      }
    }
  },
  created() {
    this.init()
  },
  methods: {

    async init() {
      try {
        this.loading = true
        await this.sleep(400)
        await this.getCourseTestList({ course_id: this.courseId })
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },

    sleep(t) {
      return new Promise((r) => setTimeout(r, t))
    },

    async getCourseTestList(data) {
      try {
        const res = await getCourseTestList(data)
        this.list = res.data
        console.log('res --------->', res)
      } catch (error) {
        throw new Error(error)
      }
    },

    async openEditCourseTestDialog(id) {
      try {
        this.testDetails.unitTestId = id
        const res = await this.getCourseTestDetails(id)
        console.log('res --------->', res)
        const result = this.courseTestDataFormatter(res.data)
        this.testDetails.data = result
        this.testDetails.backup = cloneDeep(result)
        this.visible = true
        this.$refs.createTestDialogRef.setDefaultValue(this.testDetails.data)
        console.log('result --------->', result)
      } catch (error) {
        this.$message.error('测试详情获取失败')
      }
    },

    courseTestDataFormatter(data) {
      const { test_title, pass_rate, topics } = data

      const result = {
        test_title,
        pass_rate
      }

      const convertAnswerIdToAnswerIndex = (answerIds, topics) => {
        const answers = JSON.parse(answerIds)
        const result = answers.map(num => topics.findIndex(obj => obj.id === num))
        console.log('result --------->', result)
        return result
      }

      result.data = topics.map(v => {
        const { topic_title, options, type, answer } = v
        return {
          topic_title,
          answer: convertAnswerIdToAnswerIndex(answer, options),
          type_id: value(type, 'id', 1),
          option: options.map(o => o.option)
        }
      })

      return result
    },

    async getCourseTestDetails(id) {
      const res = await getCourseTestDetails(id)
        .catch(err => {
          throw new Error(err)
        })
      if (res.code !== 200) {
        throw new Error(res.message)
      }
      return res
    },

    editCourseTest(e) {
      console.log('e --------->', e)
      const { test_title, pass_rate, data } = e
      const params = {
        unitTestId: this.testDetails.unitTestId,
        test_title,
        pass_rate
      }
      if (!isArrayEqual(data, this.testDetails.backup.data)) {
        params.data = JSON.stringify(this.topicFormatter(data))
      }

      this.editCourseTestFetch(params)
    },

    topicFormatter(data) {
      return data.map(v => {
        return {
          ...v,
          answer: JSON.stringify(v.answer)
        }
      })
    },

    async editCourseTestFetch(params) {
      this.$refs.createTestDialogRef.loading = true
      try {
        const res = await editCourseTest(params)
        console.log('res --------->', res)
        if (res.code === 200) {
          this.$message.success('修改成功')
        }
        this.refresh()
      } catch (error) {
        this.$message.error('修改失败')
      } finally {
        this.$refs.createTestDialogRef.loading = false
      }
    },

    refresh() {
      this.testDetails = this.$options.data().testDetails
      this.init()
    },

    removeCourseTest(id) {
      this.$confirm('是否删除该套测试卷', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.deleteCourseTest({ unitTestId: id })
      })
    },

    async deleteCourseTest(params) {
      try {
        const res = await deleteCourseTest(params)
        if (res.code === 200) {
          this.$message.success('删除成功')
        }
        this.refresh()
      } catch (error) {
        this.$message.error('删除失败！')
      }
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
